﻿//-----------------------------------------------------------------------
// <copyright file="RouteData.cs" company="Sławomir Rosiek">
//     Copyright (c) Sławomir Rosiek. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace Rosieks.Web.Flow
{
    using System;
    using System.Web.Mvc;
    using System.Web.Routing;


    public class RouteData
    {
        /// <summary>
        /// Initializes static members of the <see cref="T:RouteData"/> class.    
        /// </summary>
        static RouteData()
        {
            RouteData.WebflowParamName = "flowName";
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="T:RouteData"/> class.
        /// </summary>
        public RouteData()
        {
            this.Values = new RouteValueDictionary();
        }

        /// <summary>
        /// Gets or sets the name of parameter that determins name of webflow to load.
        /// </summary>
        /// <value>The name of parameter that determins name of webflow to load.</value>
        public static string WebflowParamName
        {
            get;
            set;
        }

        public string RouteName
        {
            get;
            set;
        }

        public RouteValueDictionary Values
        {
            get;
            set;
        }

        public string Url
        {
            get;
            set;
        }

        public void Register(RouteCollection routes, string flowName)
        {
            var r = routes[this.RouteName];
            var route = r as Route;
            if (r == null)
            {
                route = routes.MapRoute(this.RouteName, this.Url);

                foreach (var pair in this.Values)
                {
                    route.Defaults[pair.Key] = pair.Value;
                }

                if (!this.Values.ContainsKey("controller"))
                {
                    route.Defaults["controller"] = "Flow";
                    route.Defaults["action"] = "OnState";
                    route.DataTokens["Namespaces"] = new[] { typeof(FlowController).Namespace };
                }
            }

            if (route != null && (this.Url == null || route.Url == this.Url))
            {
                route.Defaults[RouteData.WebflowParamName] = flowName;
            }
            else
            {
                // TODO: Add exception message
                throw new ArgumentException();
            }
        }

        internal ActionResult AsRedirectResult()
        {
            return new RedirectToRouteResult(this.RouteName, this.Values);
        }
    }
}
